package com.probox.common.entity.service.product.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.text.Convert;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.product.api.domain.ProductSpecItemValueVo;
import com.probox.product.api.domain.ProductSpecItemVo;
import com.probox.product.api.domain.ProductSpecsVo;
import com.probox.common.entity.domain.product.vo.*;
import com.probox.common.entity.service.product.IProductSkuService;
import com.probox.common.entity.service.product.IProductSpecsService;
import com.probox.common.entity.service.product.IProductPropertyValuesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.probox.common.entity.mapper.product.ProductPropertyValuesMapper;
import com.probox.common.entity.domain.product.ProductPropertyValues;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品属性值Service业务层处理
 *
 *
 * @date 2021-05-28
 */
@Service
@Transactional
public class ProductPropertyValuesServiceImpl extends ServiceImpl<ProductPropertyValuesMapper, ProductPropertyValues> implements IProductPropertyValuesService {
    @Autowired
    private ProductPropertyValuesMapper productPropertyValuesMapper;

    @Autowired
    private IProductSpecsService iProductSpecsService;

    @Autowired
    private IProductSkuService iProductSkuService;

    /**
     * 查询商品属性值
     *
     * @param valuesUid 商品属性值ID
     * @return 商品属性值
     */
    @Override
    public ProductPropertyValues selectProductPropertyValuesById(Long valuesUid) {
        return this.getById(valuesUid);
    }

    /**
     * 根据商品查询相关的属性值
     *
     * @param productUid 商品uid
     * @return 商品属性值
     */
    @Override
    public List<ProductPropertyValues> queryList(Long productUid) {
        QueryWrapper<ProductPropertyValues> queryWrapper = Wrappers.query();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.eq("PRODUCT_UID", productUid);
        queryWrapper.orderByAsc("DATA_PRIORITY");
        return productPropertyValuesMapper.selectList(queryWrapper);
    }

    /**
     * 新增商品属性值
     *
     * @param productSaveVo 商品信息vo
     */
    @Override
    public void insertProductPropertyValues(ProductSaveVo productSaveVo) {
        Long[] propertyUid = productSaveVo.getPropertyUid();
        String[] property = productSaveVo.getProperty();
        if (ObjectUtil.isNotNull(propertyUid)) {
            for (int i = 0; i < propertyUid.length; i++) {
                if (StringUtils.isEmpty(property[i])) continue;
                savePropertValues(productSaveVo, null, i, propertyUid[i], property[i]);
            }
        }
    }

    /**
     * 添加sku属性值
     *
     * @param productSaveVo 商品信息vo
     * @param skuSaveVo     sku信息vo
     * @param skuUid        skuId
     * @return 属性值id
     */
    @Override
    public String insertProductSkuValues(ProductSaveVo productSaveVo, SkuSaveVo skuSaveVo, Long skuUid) {
        StringBuffer valuesUid = new StringBuffer();
        List<HashMap> data = skuSaveVo.getData();
        for (int i = 0; i < data.size(); i++) {
            HashMap map = data.get(i);
            ProductPropertyValues productPropertyValues = savePropertValues(productSaveVo, skuUid, i, Convert.toLong(map.get("id")), map.get("value_name").toString());
            valuesUid.append("," + productPropertyValues.getValuesUid());
        }
        String valuesUidSrt = valuesUid.toString();
        return valuesUidSrt.substring(1, valuesUidSrt.length());
    }

    /**
     * 修改sku属性值
     *
     * @param productSaveVo 商品信息vo
     * @param skuUid        skuUid
     */
    @Override
    public void editProductSkuValues(ProductSaveVo productSaveVo, Long skuUid) {
        UpdateWrapper<ProductPropertyValues> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", productSaveVo.getUserUid());
        updateWrapper.set("UPDATE_NAME", productSaveVo.getUserName());
        updateWrapper.set("UPDATE_TIME", productSaveVo.getTime());
        updateWrapper.in("SKU_UID", skuUid);
        boolean update = this.update(updateWrapper);
        if (!update) throw new ProductException("修改失败,请稍后再试!");
    }

    /**
     * 修改sku属性值
     *
     * @param productSaveVo 商品信息vo
     * @param productUids   uids集合
     */
    @Override
    public void editProductSkuValues(ProductSaveVo productSaveVo, Long[] productUids) {
        UpdateWrapper<ProductPropertyValues> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", productSaveVo.getUserUid());
        updateWrapper.set("UPDATE_NAME", productSaveVo.getUserName());
        updateWrapper.set("UPDATE_TIME", productSaveVo.getTime());
        updateWrapper.eq("SKU_UID", null);
        updateWrapper.in("PRODUCT_UID", productUids);
        this.update(updateWrapper);
    }

    /**
     * 获取sku的属性值
     *
     * @param skuUid skuID
     * @return
     */
    @Override
    public List<HashMap> querySkuValyesNames(Long skuUid) {
        ProductSkuQuery productSkuQuery = new ProductSkuQuery(skuUid);
        return productPropertyValuesMapper.querySkuValyesName(productSkuQuery);
    }


    /**
     * 添加属性值/sku
     *
     * @param productSaveVo 商品信息vo
     * @param skuUid        skuUid
     * @param i             索引
     * @param propertyUid   属性名id
     * @param property      属性值
     */
    private ProductPropertyValues savePropertValues(ProductSaveVo productSaveVo, Long skuUid, int i, Long propertyUid, String property) {
        ProductPropertyValues productPropertyValues = new ProductPropertyValues();
        productPropertyValues.setPlatformUid(productSaveVo.getPlatformUid());
        productPropertyValues.setProductUid(productSaveVo.getProductUid());
        productPropertyValues.setSpecsUid(propertyUid);
        productPropertyValues.setValuesName(property);
        productPropertyValues.setSkuUid(skuUid);
        productPropertyValues.setDataPriority(Long.valueOf(i));
        productPropertyValues.setDataStatus(DataStatus.valid.getKey());
        productPropertyValues.setValuesUid(productSaveVo.getUserUid());
        productPropertyValues.setUpdateUid(productSaveVo.getUserUid());
        productPropertyValues.setUpdateTime(productSaveVo.getTime());
        productPropertyValues.setUpdateName(productSaveVo.getUserName());
        boolean save = this.save(productPropertyValues);
        if (!save) throw new ProductException("添加失败,请稍后再试!");
        return productPropertyValues;
    }


    /**
     * 修改属性值
     *
     * @param productSaveVo 商品信息vo
     * @param specsUid      规格uid
     * @param valuesName    属性值
     */
    private void editropertValues(ProductSaveVo productSaveVo, Long specsUid, String valuesName) {
        UpdateWrapper<ProductPropertyValues> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("UPDATE_UID", productSaveVo.getUserUid());
        updateWrapper.set("UPDATE_TIME", productSaveVo.getTime());
        updateWrapper.set("UPDATE_NAME", productSaveVo.getUserName());
        if (StringUtils.isNotEmpty(valuesName)) updateWrapper.set("VALUES_NAME", valuesName);
        updateWrapper.set("DATA_STATUS", productSaveVo.getDataStatus());
        updateWrapper.eq("PRODUCT_UID", productSaveVo.getProductUid());
        updateWrapper.eq("SPECS_UID", specsUid);
        updateWrapper.eq("PLATFORM_UID", productSaveVo.getPlatformUid());
        boolean update = this.update(updateWrapper);
        if (!update) throw new ProductException("修改失败,请稍后再试!");
    }

    /**
     * 修改商品属性值
     *
     * @param productSaveVo 商品信息vo
     */
    @Override
    public void updateProductPropertyValues(ProductSaveVo productSaveVo) {
        Long[] propertyUid = productSaveVo.getPropertyUid();
        String[] property = productSaveVo.getProperty();
        if (ObjectUtil.isNotNull(propertyUid)) {
            List<ProductPropertyValues> productPropertyValues = queryList(productSaveVo.getProductUid());
            HashMap map = new HashMap();
            productPropertyValues.stream().forEach(values -> map.put(values.getSpecsUid(), values.getValuesName()));
            for (int i = 0; i < propertyUid.length; i++) {
                Long uid = propertyUid[i];
                if (StringUtils.isEmpty(property[i])) {
                    if (ObjectUtil.isNotEmpty(map.get(uid))) {
                        productSaveVo.setDataStatus(DataStatus.delete.getKey());
                        editropertValues(productSaveVo, propertyUid[i], null);
                    }
                } else {
                    productSaveVo.setDataStatus(DataStatus.valid.getKey());
                    if (ObjectUtil.isNotEmpty(map.get(uid)))
                        editropertValues(productSaveVo, propertyUid[i], property[i]);
                    else savePropertValues(productSaveVo, null, i, propertyUid[i], property[i]);
                }
            }
        }
    }

    /**
     * 获取编辑后的属性值
     *
     * @param productUid 商品uid
     * @return
     */
    @Override
    public String[] selectProductPropertyValuesArray(Long productUid) {
        String[] property = null;
        HashMap map = new HashMap();
        Long[] longs = iProductSpecsService.selectProductPropertyArray();
        if (ObjectUtil.isNotEmpty(longs)) {
            int length = longs.length;
            property = new String[longs.length];
            List<ProductPropertyValues> productPropertyValues = queryList(productUid);
            if (ObjectUtil.isNotEmpty(productPropertyValues)) {
                productPropertyValues.stream().forEach(propertyValue -> map.put(propertyValue.getSpecsUid(), propertyValue.getValuesName()));
            }
            for (int i = 0; i < length; i++) {
                if (ObjectUtil.isNotEmpty(map.get(longs[i]))) property[i] = map.get(longs[i]).toString();
                else property[i] = "";
            }
        }
        return property;
    }

    /**
     * 查询集合的属性值和属性名
     *
     * @param productUid
     * @return
     */
    @Override
    public List<ProductProerytyVo> queryValuesName(Long productUid) {
        return productPropertyValuesMapper.queryValuesName(productUid);
    }


    /**
     * 返回sku规格集合
     *
     * @param productUid 商品uid
     * @return
     */
    @Override
    public List<SkuSpecsVo> getSkuSpecsVoList(Long productUid) {
        List<SkuSpecsVo> list = new ArrayList<>();
        ProductSkuQuery productSkuQuery = new ProductSkuQuery(null, productUid);
        List<SkuSpecsVo> skuSpecsVos = productPropertyValuesMapper.querySpecsUid(productSkuQuery);
        if (ObjectUtil.isNotEmpty(skuSpecsVos)) {
            skuSpecsVos.forEach(vo -> {
                ProductSkuQuery productSkuQuerys = new ProductSkuQuery(productUid, vo.getSpecsUid(), null);
                vo.setValues(productPropertyValuesMapper.queryValuesUid(productSkuQuerys));
                list.add(vo);
            });
        }
        return list;
    }

    /**
     *  获取商品sku规格信息
     * @param productUid
     * @return
     */
    @Override
    public ProductSpecsVo getSpecsVo(Long productUid) {
        ProductSpecsVo specsVo = new ProductSpecsVo();
        specsVo.setMsg("ok");
        specsVo.setStatus(1);
        List<ProductSpecItemVo> specifications = new ArrayList<>();
        List<SkuSpecsVo> skuSpecsVos = getSkuSpecsVoList(productUid);
        if (ObjectUtil.isNotEmpty(skuSpecsVos)) {
            skuSpecsVos.forEach(vo -> {
                ProductSpecItemVo itemVo = new ProductSpecItemVo();
                itemVo.setName(vo.getSpecsName());
                itemVo.setItem(getItemValueVo(vo));
                specifications.add(itemVo);
            });
        }
        specsVo.setSpecifications(specifications);
        return specsVo;
    }
    private List<ProductSpecItemValueVo> getItemValueVo(SkuSpecsVo vo){

        List<ProductSpecItemValueVo> item = new ArrayList<>();
        List<HashMap> values = vo.getValues();
        if(ObjectUtil.isEmpty(values)) return item;
        values.forEach(value ->{
            ProductSpecItemValueVo valueVo = new ProductSpecItemValueVo();
            valueVo.setName(value.get("text").toString());
            item.add(valueVo);
        });
        return item;
    }

    /**
     * 是否使用
     * @param specsUid
     * @return
     */
    @Override
    public boolean usePro(Long specsUid){
        QueryWrapper<ProductPropertyValues> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SPECS_UID",specsUid);
        queryWrapper.eq("DATA_STATUS",DataStatus.valid.getKey());
        Integer integer = productPropertyValuesMapper.selectCount(queryWrapper);
        if(integer > 0) return true;
        else return false;
    }

}
